#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

#include "DHTesp.h" // Click here to get the library: http://librarymanager/All#DHTesp

#ifdef ESP32
#pragma message(THIS EXAMPLE IS FOR ESP8266 ONLY!)
#error Select ESP8266 board.
#endif

//温度
DHTesp dht;

#define DHTPIN 2

unsigned long dhttime = 0;
int dhtdelay = 5000;

//wifi
#ifndef STASSID
#define STASSID "Xiaomi_2G_free" //你的wifi名称
#define STAPSK  ""  //你的wifi密码  我家没有密码所以没有了
#endif

const char* ssid = STASSID;
const char* password = STAPSK;

ESP8266WebServer server(80);

const int led = 13;
const int relay1 = 14;


//eeprom
#include <EEPROM.h>

int automodeADDR = 0 ; //内存地址0开始
int Temp1ADDR  = 1 ; //浮点数占4个位
int Temp2ADDR  = 5 ; //浮点数占4个位


bool automode ;
float T1 ; //浮点数占4个位
float T2 ; //浮点数占4个位


//EEPROM写入模式 布尔
void writeautomode(bool temp)
{
  EEPROM.put(automodeADDR, temp);
  EEPROM.commit();
  Serial.println("Write MODE:" + (String)temp + " OK!\n" );
}
//EEPROM写入T1 浮点数
void writeT1(float temp)

{
  EEPROM.put(Temp1ADDR, temp);
  EEPROM.commit();
  Serial.println("Write T1:" + (String)temp + " OK!\n" );
}
//EEPROM写入T2 浮点数
void writeT2(float temp)
{
  EEPROM.put(Temp2ADDR, temp);
  EEPROM.commit();
  Serial.println("Write T2:" + (String)temp + " OK!\n" );
}


//EEPROM读取模式
void readautomode ()
{
  EEPROM.get(automodeADDR, automode);
  Serial.println((String)automode + "\n" );
  if ( automode != NULL) {
    Serial.println("MODE:" + (String)automode + "\n" );
  }
  else {
    writeautomode(true);
  }


}
//EEPROM读取T1
void readT1 ()
{
  EEPROM.get(Temp1ADDR, T1);
  Serial.println((String)T1 + "\n" );
  if (T1 != NULL) {
    Serial.println("readT1:" + (String)T1 + "\n" );
  }
  else {
    writeT1(11.0);
  }
}

//EEPROM读取T2
void readT2()
{
  EEPROM.get(Temp2ADDR, T2);
  Serial.println((String)T2 + "\n" );
  if (T2 != NULL) {
    Serial.println("readT2:" + (String)T2 + "\n" );
  }
  else {
    writeT2(66.0);
  }
}


//eeprom

void handleRoot() {
  digitalWrite(led, 1);
  server.send(200, "text/plain", "hello from esp8266!\r\n");
  digitalWrite(led, 0);
}


String text = "";

float humidity = 0.0;
float temperature = 0.0;

// bool automode = true ;
bool run1 = true;
bool run2 = false;
float defaulthumidity;
float defaulttemperature;

int times = 0;
bool runif = false;
unsigned long  lasttime = 0;
void relayon() {
  if (times == 0) {
    digitalWrite(led, 1);
    digitalWrite(relay1, 1);
    if (server.uri()) {
      server.send(200, "text/plain", "relay always on\r\n");
    }
    digitalWrite(led, 0);
  }
  else {
    digitalWrite(led, 1);
    digitalWrite(relay1, 1);
    if (server.uri()) {
      server.send(200, "text/plain", "relay on:" + (String)times + "\r\n");
    }
    digitalWrite(led, 0);
    lasttime = millis();
    runif  = true;
  }
}

void setconfig() {
  if  (server.args() > 0) {
    for (int i = 0; i < server.args(); i++) {
      String tout = "";

      if (server.argName(i) == "time") {
        times = server.arg(i).toInt();
        if (times > 0 ) {
          tout += "times:" + (String)times + " set is ok \n\r";
        }
        else {
          times = 0;
          tout += "times: 0 set is ok ";
        }
      }

      if (server.argName(i) == "automode") {
        String mode1 = server.arg(i);
        if (mode1 == "1" ) {
          automode = true;
          writeautomode(true); //写入EEPROM
          run1 = true;
          run2 = false;
          tout += "mode:auto\n\r";
        }
        else {
          automode = false;
          writeautomode(false); //写入EEPROM
          tout += "mode:hande\n\r";
        }
      }

      if (server.argName(i) == "H") {
        int tem1 = server.arg(i).toInt();
        if (tem1 > 0) {
          defaulthumidity = (float)tem1 ;
          writeT2(defaulthumidity ); //写入eeprom
          tout += "defaulthumidity:" + (String)defaulthumidity  + "\n\r";
        }
        else {
          ;
        }
      }

      if (server.argName(i) == "T") {
        int tem2 = server.arg(i).toInt();
        if (tem2 > 0) {
          defaulttemperature = (float)tem2 ;
          writeT1(defaulttemperature ); //写入eeprom
          tout += "defaulttemperature:" + (String)defaulttemperature  + "\n\r";
        }
        else {
          ;
        }
      }


      Serial.println(tout);
      server.send(200, "text/plain", tout);
    }
  }
}

void relayoff() {
  digitalWrite(led, 1);
  digitalWrite(relay1, 0);
  if (server.uri()) {
    server.send(200, "text/plain", "relay is off\r\n");
  }
  digitalWrite(led, 0);
  runif  = false;
}

void showtemp() {

  server.send(200, "text/plain", text);
}

void handleNotFound() {
  digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  digitalWrite(led, 0);
}

void setup(void) {
  //初始换EEPROM 512可用空间长度
  EEPROM.begin(512);
  delay(500);
  //最好加上这个延时
  readautomode();
  readT1();
  readT2();
  defaulthumidity = T2;
  defaulttemperature = T1;
  dht.setup(DHTPIN, DHTesp::DHT11);
  pinMode(led, OUTPUT);
  pinMode(relay1, OUTPUT); //
  digitalWrite(led, 0);
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);


  server.on("/on", relayon);

  server.on("/config", setconfig);

  server.on("/off", relayoff);

  server.on("/temp", showtemp);

  server.on("/inline", []() {
    server.send(200, "text/plain", "this works as well");
  });

  server.on("/gif", []() {
    static const uint8_t gif[] PROGMEM = {
      0x47, 0x49, 0x46, 0x38, 0x37, 0x61, 0x10, 0x00, 0x10, 0x00, 0x80, 0x01,
      0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x2c, 0x00, 0x00, 0x00, 0x00,
      0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x19, 0x8c, 0x8f, 0xa9, 0xcb, 0x9d,
      0x00, 0x5f, 0x74, 0xb4, 0x56, 0xb0, 0xb0, 0xd2, 0xf2, 0x35, 0x1e, 0x4c,
      0x0c, 0x24, 0x5a, 0xe6, 0x89, 0xa6, 0x4d, 0x01, 0x00, 0x3b
    };
    char gif_colored[sizeof(gif)];
    memcpy_P(gif_colored, gif, sizeof(gif));
    // Set the background to a random set of colors
    gif_colored[16] = millis() % 256;
    gif_colored[17] = millis() % 256;
    gif_colored[18] = millis() % 256;
    server.send(200, "image/gif", gif_colored, sizeof(gif_colored));
  });

  server.onNotFound(handleNotFound);

  /////////////////////////////////////////////////////////
  // Hook examples
  /*
    server.addHook([](const String & method, const String & url, WiFiClient * client, ESP8266WebServer::ContentTypeFunction contentType) {
      (void)method;      // GET, PUT, ...
      (void)url;         // example: /root/myfile.html
      (void)client;      // the webserver tcp client connection
      (void)contentType; // contentType(".html") => "text/html"
      Serial.printf("A useless web hook has passed\n");
      Serial.printf("(this hook is in 0x%08x area (401x=IRAM 402x=FLASH))\n", esp_get_program_counter());
      return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE;
    });

    server.addHook([](const String&, const String & url, WiFiClient*, ESP8266WebServer::ContentTypeFunction) {
      if (url.startsWith("/fail")) {
        Serial.printf("An always failing web hook has been triggered\n");
        return ESP8266WebServer::CLIENT_MUST_STOP;
      }
      return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE;
    });

    server.addHook([](const String&, const String & url, WiFiClient * client, ESP8266WebServer::ContentTypeFunction) {
      if (url.startsWith("/dump")) {
        Serial.printf("The dumper web hook is on the run\n");

        // Here the request is not interpreted, so we cannot for sure
        // swallow the exact amount matching the full request+content,
        // hence the tcp connection cannot be handled anymore by the
        // webserver.
    #ifdef STREAMSEND_API
        // we are lucky
        client->sendAll(Serial, 500);
    #else
        auto last = millis();
        while ((millis() - last) < 500) {
          char buf[32];
          size_t len = client->read((uint8_t*)buf, sizeof(buf));
          if (len > 0) {
            Serial.printf("(<%d> chars)", (int)len);
            Serial.write(buf, len);
            last = millis();
          }
        }
    #endif
        // Two choices: return MUST STOP and webserver will close it
        //                       (we already have the example with '/fail' hook)
        // or                  IS GIVEN and webserver will forget it
        // trying with IS GIVEN and storing it on a dumb WiFiClient.
        // check the client connection: it should not immediately be closed
        // (make another '/dump' one to close the first)
        Serial.printf("\nTelling server to forget this connection\n");
        static WiFiClient forgetme = *client; // stop previous one if present and transfer client refcounter
        return ESP8266WebServer::CLIENT_IS_GIVEN;
      }
      return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE;
    });

    // Hook examples
    /////////////////////////////////////////////////////////
  */
  server.begin();
  Serial.println("HTTP server started");
}

void loop(void) {
  server.handleClient();
  MDNS.update();
  if (automode == true ) {

    if ( humidity <= defaulthumidity  || temperature >= defaulttemperature) {
      if (run1 == true) {
        relayon();
        run1 = false;
        run2 = true;
      }
    }
    else {
      if (run2 ) {
        relayoff();
        run2 = false;
        run1 = true;
      }
    }
  }


  else {
    ;
  }
  //循环中放置这个判断语句是否在一段时间内执行程序
  if (runif == true) {
    if (millis() - lasttime > times) {

      digitalWrite(relay1, 0);
      lasttime = millis();
      runif  = false;
    }
  }


  if (millis() - dhttime > dhtdelay) {
    //delay(dht.getMinimumSamplingPeriod());

    humidity = dht.getHumidity();
    temperature = dht.getTemperature();
    text = "H:" + (String)humidity + ",T:" + temperature + "\n" ;
    text += "defaulthumidity:" + (String)defaulthumidity + ",defaulttemperature:" + (String)defaulttemperature + "\n";
    text += "mode:" + (String)automode ;
    Serial.println(text);
    /*
       Serial.print(dht.getStatusString());
       Serial.print("\t");
       Serial.print(humidity, 1);
       Serial.print("\t\t");
       Serial.print(temperature, 1);
       Serial.print("\t\t");
       Serial.print(dht.toFahrenheit(temperature), 1);
       Serial.print("\t\t");
       Serial.print(dht.computeHeatIndex(temperature, humidity, false), 1);
       Serial.print("\t\t");
       Serial.println(dht.computeHeatIndex(dht.toFahrenheit(temperature), humidity, true), 1);
       //delay(2000);
    */
    dhttime = millis();

  }
}